package com.zdkj.subway.check.controller.subwayRat.conductorDifferences.cheZhan;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zdkj.common.security.annotation.Inner;
import com.zdkj.subway.check.entity.*;
import com.zdkj.subway.check.enums.ResultDetailMsg;
import com.zdkj.subway.check.fegin.SubwayStmService;
import com.zdkj.subway.check.mapper.FareDifferencesInAuditMapper;
import com.zdkj.subway.check.mapper.SwAuCenterConductorAmountDifferenceMapper;
import com.zdkj.subway.check.mapper.SwAuStDiffNoticeMapper;
import com.zdkj.subway.check.mapper.SwAuStationTicketDifferenceMapper;
import com.zdkj.subway.check.result.Result;
import com.zdkj.subway.check.service.SwStReportqueryStationincomeService;
import com.zdkj.subway.check.util.UserInfo;
import com.zdkj.subway.check.util.CheckAccount;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import com.zdkj.common.core.util.R;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 车站票款差异
 */
@Slf4j
@RestController
@Api(value = "check", tags = "车站票款差异")
@RequestMapping("/check")
public class SwAuStationTicketDifferenceController {
    @Resource
    SwAuStationTicketDifferenceMapper swAuStationTicketDifferenceMapper;
    @Resource
    SwAuStDiffNoticeMapper swAuStDiffNoticeMapper;
    @Resource
    FareDifferencesInAuditMapper fareDifferencesInAuditMapper;
    @Resource
    SwAuCenterConductorAmountDifferenceMapper swAuCenterConductorAmountDifferenceMapper;
    @Resource
    SubwayStmService subwayStmService;
    @Resource
    SwStReportqueryStationincomeService swStReportqueryStationincomeService;

    /**
     * 车站票款差异信息查询
     * @param page
     * @param swAuStationTicketDifference
     * @param param
     * @return
     */
    @RequestMapping("/getSwAuStationTicketDifferenceList")
    @ApiOperation(value = "车站票款差异信息查询", notes = "车站票款差异信息查询")
    public Page getSwAuStationTicketDifferenceList(Page page, SwAuStationTicketDifference swAuStationTicketDifference, @RequestParam Map<String,Object> param){
        List<Map<String,Object>> res=swAuStationTicketDifferenceMapper.getSwAuStationTicketDifferenceList(param);
        page.setData(res,true);
        return page;
    }

    /**
     * 车站票款差异信息编辑
     * @param swAuStationTicketDifference
     * @param param
     * @return
     */
    @RequestMapping("/updateSwAuStationTicketDifference")
    @ApiOperation(value = "车站票款差异信息编辑", notes = "车站票款差异信息编辑")
    public Result updateSwAuStationTicketDifference(SwAuStationTicketDifference swAuStationTicketDifference, @RequestParam Map<String,Object> param){
        Result res=new Result(ResultDetailMsg.OK);
        try{
            swAuStationTicketDifference.setUpdateTime(new Date());
            int af=swAuStationTicketDifferenceMapper.updateById(swAuStationTicketDifference);
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("修改失败");
        }
        return res;
    }

	/**
     * 通过id列表删除售票员票款差异审核主页
     * @param ids ids
     * @return R
     */
    @ApiOperation(value = "通过id列表删除车站票款差异通知主页", notes = "通过id列表删除车站票款差异通知主页")
    //@SysLog("通过id列表删除售票员票款差异审核主页" )
    @RequestMapping("/removeSwAuStationTicketDifferenceByIds" )
    //@Transactional(rollbackFor = Exception.class)
    public R removeByIds(@RequestParam(value = "ids") List<Integer> ids) {
        return R.ok(swAuStationTicketDifferenceMapper.deleteBatchIds(ids));
    }

    /**
     * 车站票款差异信息新增
     * @param swAuStationTicketDifference
     * @param param
     * @return
     */
    @RequestMapping("/addSwAuStationTicketDifference")
    @ApiOperation(value = "车站票款差异信息新增", notes = "车站票款差异信息新增")
    public Result addSwAuStationTicketDifference(SwAuStationTicketDifference swAuStationTicketDifference, @RequestParam Map<String,Object> param){
        Result res=new Result(ResultDetailMsg.OK);
        try{
            //未通知
            swAuStationTicketDifference.setIsAddNotice("0");
            swAuStationTicketDifference.setSettleStatus("0");//未结算
            swAuStationTicketDifference.setCreatorId(UserInfo.getId());
            swAuStationTicketDifference.setCreatorName(UserInfo.getUserName());
            swAuStationTicketDifference.setCreateTime(new Date());
            swAuStationTicketDifference.setUpdateTime(new Date());
            swAuStationTicketDifference.setDataSource("2");//线网
            int af=swAuStationTicketDifferenceMapper.addSwAuStationTicketDifference(swAuStationTicketDifference);
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("修改失败");
        }
        return res;
    }

    /**
     * 通知数据
     * @param ids
     * @return
     */
    @RequestMapping("/noticeSwAuStationTicketDifference")
    @ApiOperation(value = "通知数据", notes = "通知数据")
    public Result noticeSwAuStationTicketDifference(String ids){
        Result res=new Result(ResultDetailMsg.OK);
        try{
            QueryWrapper<SwAuStationTicketDifference> queryWrapper=new QueryWrapper<>();
			int iReplyPeriod = CheckAccount.getStationNoticeLimit();
            //queryWrapper.in("id",ids);
            queryWrapper.in("id",ids.split(","));
            List<SwAuStationTicketDifference> swAuStationTicketDifferences = swAuStationTicketDifferenceMapper.selectList(queryWrapper);
            for(SwAuStationTicketDifference swAuStationTicketDifference:swAuStationTicketDifferences){
                SwAuStDiffNotice swAuStDiffNotice=new SwAuStDiffNotice();

                swAuStDiffNotice.setRelationid(swAuStationTicketDifference.getId());
                //线路
                swAuStDiffNotice.setLineCode(swAuStationTicketDifference.getLineCode());
                //站点
                swAuStDiffNotice.setStationCode(swAuStationTicketDifference.getStationCode());
                //收入日期
                swAuStDiffNotice.setIncomeTime(swAuStationTicketDifference.getIncomeTime());
                //售票员工号
                swAuStDiffNotice.setConductorJobNo(swAuStationTicketDifference.getConductorJobNo());
                //售票员名称
                swAuStDiffNotice.setConductorPersonName(swAuStationTicketDifference.getConductorPersonName());
                //现金营收总金额
                swAuStDiffNotice.setCashReceiptsAmount(swAuStationTicketDifference.getCashReceiptsAmount());
                //现金缴款单金额
                swAuStDiffNotice.setCashPayAmount(swAuStationTicketDifference.getCashPayAmount());
                //差异金额
                swAuStDiffNotice.setDiffAmount(swAuStationTicketDifference.getDiffAmount());
                //下发状态
                swAuStDiffNotice.setSendState("0");
                swAuStDiffNotice.setSendTime(null);
                swAuStDiffNotice.setReplyPeriod(iReplyPeriod);//回复期限
                //通知状态
                swAuStDiffNotice.setNoticeState("0");
                swAuStDiffNotice.setAppealState("1");//通知时默认待申诉1
                swAuStDiffNotice.setAppealType("3");//申诉类型默认为未申诉
                //审批状态 待审批
                swAuStDiffNotice.setAuditSate("1");
                //补款状态
                swAuStDiffNotice.setSuappStatus("0");
                swAuStDiffNotice.setSuappTime(null);
                swAuStDiffNotice.setCreatorId(UserInfo.getId());
                swAuStDiffNotice.setAppealPersonCode(UserInfo.getUserCode());
                swAuStDiffNotice.setAppealPersonId(UserInfo.getId());
                swAuStDiffNotice.setAppealPersonCode(UserInfo.getUserCode());
                //swAuStDiffNotice.setAppealType("");
                swAuStDiffNotice.setCreateTime(new Date());

                int af=swAuStDiffNoticeMapper.addSwAuStDiffNotice(swAuStDiffNotice);

                swAuStationTicketDifference.setIsAddNotice("1");
                swAuStationTicketDifference.setNoticeTime(new Date());
                swAuStationTicketDifferenceMapper.updateById(swAuStationTicketDifference);
            }
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_INSERT_ERROR);
            res.setMsg("通知失败");
        }
        return res;
    }

    /**
     * 车站结算
     * @param ids
     * @return
     */
    @RequestMapping("/chezhanJieSuanSwAuStationTicketDifference")
    @ApiOperation(value = "车站结算", notes = "车站结算")
    public Result chezhanJieSuanSwAuStationTicketDifference(String ids){
        Result res=new Result(ResultDetailMsg.OK);
        try{
            for(String id:ids.split(",")){
                SwAuStationTicketDifference swAuStationTicketDifference = swAuStationTicketDifferenceMapper.selectById(Integer.parseInt(id));
                //结算状态 已结算
                swAuStationTicketDifference.setSettleStatus("1");
                swAuStationTicketDifference.setUpdateTime(new Date());
                swAuStationTicketDifferenceMapper.updateById(swAuStationTicketDifference);//修改
            }
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("车站结算失败");
        }
        return res;
    }

    /**
     * 现金营收总金额--废弃
     * @param swAuStationTicketDifference
     * @return
     */
    @RequestMapping("/xianjinYingShouAllAmount")
    @ApiOperation(value = "现金营收总金额--废弃", notes = "现金营收总金额--废弃")
    public Result xianjinYingShouAllAmount(SwAuStationTicketDifference swAuStationTicketDifference){
        Result res=new Result(ResultDetailMsg.OK);
        try{
            //根据线路、站点、收入日期 查询 TVM票款差异审核表
            QueryWrapper<FareDifferencesInAudit> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("line_code",swAuStationTicketDifference.getLineCode());
            queryWrapper.eq("station_code",swAuStationTicketDifference.getStationCode());
            queryWrapper.ge("record_time",swAuStationTicketDifference.getSettleBeginDate());
            queryWrapper.le("record_time",swAuStationTicketDifference.getSettleEndDate());
            queryWrapper.select("ifnull(sum(system_money),0) as system_money_all");
            List<Map<String, Object>> maps = fareDifferencesInAuditMapper.selectMaps(queryWrapper);
            BigDecimal system_money_all=new BigDecimal(0);
            if(maps.size()>0){
                system_money_all = (BigDecimal)maps.get(0).get("system_money_all");
            }

            //根据线路、站点、收入日期 查询 售票员票款差异审核表
            QueryWrapper<SwAuCenterConductorAmountDifference> queryWrapper2=new QueryWrapper<>();
            queryWrapper2.eq("line_code",swAuStationTicketDifference.getLineCode());
            queryWrapper2.eq("station_code",swAuStationTicketDifference.getStationCode());
            queryWrapper2.ge("record_time",swAuStationTicketDifference.getSettleBeginDate());
            queryWrapper2.le("record_time",swAuStationTicketDifference.getSettleEndDate());
            queryWrapper2.select("ifnull(sum(paid_amount),0) as paid_amount_all");
            List<Map<String, Object>> maps2 = swAuCenterConductorAmountDifferenceMapper.selectMaps(queryWrapper2);
            BigDecimal paid_amount_all=new BigDecimal(0);
            if(maps2.size()>0){
                paid_amount_all = (BigDecimal)maps2.get(0).get("paid_amount_all");
            }
            res.setData(system_money_all.add(paid_amount_all));
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("获取金额失败");
        }
        return res;
    }


    /**
     * 获取车站营收日报表总金额
     * @param
     * @return
     */
    @ApiOperation(value = "获取车站营收日报表总金额", notes = "获取车站营收日报表总金额")
    @GetMapping("/cheZhanYingShouAllAmount")
    public Result cheZhanYingShouAllAmount(SwAuStationTicketDifference swAuStationTicketDifference){
        Result res=new Result(ResultDetailMsg.OK);
        try{
            
			//通过线路站点收入日期查询车站营收日报表
			/*
            LambdaQueryWrapper<SwStReportqueryStationincome> lambda = new QueryWrapper<SwStReportqueryStationincome>().lambda();
            lambda.eq(SwStReportqueryStationincome::getLineCode,swAuStationTicketDifference.getLineCode());
            lambda.eq(SwStReportqueryStationincome::getStationCode,swAuStationTicketDifference.getStationCode());
            lambda.eq(SwStReportqueryStationincome::getStatisticsDate,DateFormat.dateTOLocalDate(swAuStationTicketDifference.getIncomeTime()));
            BigDecimal total = swStReportqueryStationincomeService.getOne(lambda).getTotal();
            BigDecimal stationReceiptsAmount = new BigDecimal(0);
            if(total!=null){
                stationReceiptsAmount = total;
                res.setData(stationReceiptsAmount);
            }else {
                res.setData(stationReceiptsAmount);
            }*/
			// 调整为根据线路、站点、开始日期、结束日期计算总和,考虑长周期结算问题
			QueryWrapper<SwStReportqueryStationincome> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("line_code",swAuStationTicketDifference.getLineCode());
            queryWrapper.eq("station_code",swAuStationTicketDifference.getStationCode());
			queryWrapper.eq("del_flag","0");
            queryWrapper.ge("statistics_date",swAuStationTicketDifference.getSettleBeginDate());
            queryWrapper.le("statistics_date",swAuStationTicketDifference.getSettleEndDate());			
            queryWrapper.select("ifnull(sum(total),0) as total");
            List<SwStReportqueryStationincome> list = swStReportqueryStationincomeService.list(queryWrapper);
            BigDecimal total=new BigDecimal(0);
            if(list!=null && list.size()>0){
                total = list.get(0).getTotal();
            }
			res.setData(total);
        }catch (Exception e){
            log.error("{}",e);
            res.setMsg("获取金额失败");
        }
        return res;
    }


    /**
     * 添加生成的车站票款差异
     * @param swAuStationTicketDifferences
     * @return
     */
    @Inner
    @PostMapping("/innerSaveBatch")
    @ApiOperation(value = "添加生成的车站票款差异", notes = "添加生成的车站票款差异")
    public Result innerSave(@RequestBody List<SwAuStationTicketDifference> swAuStationTicketDifferences){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            swAuStationTicketDifferences.forEach(item -> {
                swAuStationTicketDifferenceMapper.addSwAuStationTicketDifference(item);
            });
        } catch (Exception e) {
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_INSERT_ERROR);
            res.setMsg("车站添加失败");
        }
        return res;
    }

}
